<?php
$errors  = array();
$values  = array();
$success = '';
$errmsg  = '';

$fileconf = "../application/config/config.php";
$filedata = "../application/config/database.php";
$write = is_writable("../../");

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    foreach($_POST as $key => $value) {
        $values[$key] = trim(stripslashes($value)); // basic input filter
    }

    if (check_input($values['base_url']) == false) { 
        $errors['base_url'] = 'Sisesta URLi aadress';
    }
	
    if (!file_exists($filedata)) {
            $errors['filedata'] = 'Viga, database.php faili ei leitud.';
    }

    if (!file_exists($fileconf)) {
            $errors['fileconf'] = 'Viga, config.php faili ei leitud.';
    }

    $connect = mysql_connect($values['localhost'],$values['username'],$values['password']);
    if (!$connect) {
            $errors['connect'] = 'Andmebaasiga ei saadud &#252;hendust: ' . mysql_error();
    }

    $createtabel = mysql_query("CREATE DATABASE IF NOT EXISTS $values[database]",$connect);
    if (!$createtabel){
            $errors['createtable'] = 'Andmebaasi ei saadud luua';
    }

    if(!$write){
            $errors['write'] = '&#220;lemkataloog ei ole kirjutamis&#245;igusega';
    }

	
    if (sizeof($errors) == 0) {
        // you can process your for here and redirect or show a success message
		mysql_select_db($values['database'], $connect);
                
		$users_sql = 
                "CREATE TABLE IF NOT EXISTS `users` (
		  `ID` int(8) unsigned NOT NULL AUTO_INCREMENT,
		  `firstname` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL,
		  `lastname` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL,
		  `email` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
		  `password` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
		  `twitter_id` int(20) DEFAULT NULL,
		  PRIMARY KEY (`ID`)
		) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;";
                
                $filters_sql =
                "CREATE TABLE IF NOT EXISTS `clientFilter` (
                  `ID` int(8) NOT NULL AUTO_INCREMENT,
                  `clientID` int(8) NOT NULL,
                  `filterData` longtext COLLATE utf8_unicode_ci NOT NULL,
                  `interval` int(10) NOT NULL,
                  `lastFetched` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                  `title` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
                  `active` tinyint(4) NOT NULL DEFAULT '1',
                  PRIMARY KEY (`ID`)
                ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;";
                
                $content_sql =
                "CREATE TABLE IF NOT EXISTS `content` (
                  `ID` int(11) NOT NULL AUTO_INCREMENT,
                  `filterID` int(11) NOT NULL,
                  `title` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
                  `url` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
                  `text` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
                  `providerName` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
                  `fetchedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                  PRIMARY KEY (`ID`),
                ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;";

                
		mysql_query($users_sql, $connect);	
                mysql_query($filters_sql, $connect); 	
                mysql_query($content_sql, $connect); 
                
		mysql_close($connect); 	
		
		replace($fileconf,array("%base_url%" => $values['base_url']));
		replace($filedata,array("%localhost%" => $values['localhost'], "%username%" => $values['username'], "%password%" => $values['password'], "%database%" => $values['database']));
		
		recurse_copy("../application","../../application");
		recurse_copy("../system","../../system");
		rrmdir("../application");
		rrmdir("../system");
	
        $values = array(); // empty values array
        $success = 'Installeerimine &#245;nnestus. Kustutage n&#252;&#252;d install kaust &#228;ra<br />';
    } else {
        // one or more errors
        foreach($errors as $error) {
            $errmsg .= $error . '<br />';
        }
    }
}

function check_input($input) {
    if (strlen($input) == 0) {
        return false;
    } else {
        // TODO: other checks?

        return true;
    }
}

// Kasutaja poolt sisestatud parameetrite asendamine failidesse

function replace($filename, $array)
{
	$f = fopen($filename, "r+");
	$data = file_get_contents($filename, true);
	foreach($array as $key => $val)
	{
		$data = str_replace($key,$val,$data);
	}
	file_put_contents($filename,$data);
	fclose($f);
}

// Kaustade ja failide kopeerimine

function recurse_copy($src,$dst) {
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            if ( is_dir($src . '/' . $file) ) {
                recurse_copy($src . '/' . $file,$dst . '/' . $file);
            }
            else {
                copy($src . '/' . $file,$dst . '/' . $file);
            }
        }
    }
    closedir($dir);
} 

// Kaustade ja failide rekursiivne kustutamine

function rrmdir($dir) {
   if (is_dir($dir)) {
     $objects = scandir($dir);
     foreach ($objects as $object) {
       if ($object != "." && $object != "..") {
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
       }
     }
     reset($objects);
     rmdir($dir);
   }
} 
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Focus - Avaleht</title>
<link href="http://fonts.googleapis.com/css?family=PT+Sans|Changa+One" rel="stylesheet" type="text/css">
<link href="../styles/common.css" rel="stylesheet" type="text/css" />
<link href="../styles/messages.css" rel="stylesheet" type="text/css" />
<link href="../coin-slider/coin-slider-styles.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../coin-slider/coin-slider.js"></script>
<script type="text/javascript" src="../js/focus.messages.js"></script>
<script type="text/javascript" src="../js/focus.core.js"></script>
</head>
<body>
<div class="content page-small">
  <h2>Paigaldamine</h2>
  <!-- Mingi tervitus jms &#252;ldised juhendid. -->
  <p>Te hakkate paigaldama Focus rakendust. Selleks palume teil t&#228;ita allolevad v&#228;ljad.</p>
 
        
    <?php if ($errmsg != ''): ?>
      <div class="form-error-message">
        <p style="color: red;"><b>Tekkisid j&#228;rgmised vead:</b><br />
        <?php echo $errmsg; ?>
        </p>
      </div>
    <?php endif; ?>
	
	<?php if ($success != ''): ?>
      <div class="form-error-message">
        <p style="color: green;">
        <?php echo $success; ?>
        </p>
      </div>
    <?php endif; ?>
	
	
   
  <form action="#" method="post" enctype="multipart/form-data" name="install" class="form" id="install">
    <div class="form-row">
        <label>URLi aadress
          <input name="base_url" type="text" class="input-field" id="base_url" tabindex="1" value="http://www.example.com" />
        </label>
        <div class="field-description">URLi aadress, kus keskkond t&#246;&#246;le hakkab. Lokaalselt http://localhost</div>
    </div>
    <div class="form-row">
        <label>Andmebaasi nimi
            <input name="database" type="text" class="input-field" id="database" tabindex="2" value="focus" />
        </label>
        <div class="field-description">Kui sellise nimega andmebaasi ei eksisteeri, siis see luuakse.</div>
    </div>
    <div class="form-row">
          <label>MySQL kasutajatunnus
            <input name="username" type="text" class="input-field" id="username" tabindex="3" />
      </label>
	  <div class="field-description">Teie andmebaasi kasutajanimi.</div>
    </div>
    <div class="form-row">
          <label>MySQL parool
            <input name="password" type="password" class="input-field" id="password" tabindex="4" />
      </label>
	  <div class="field-description">Teie andmebaasi parool.</div>
    </div>
    <div class="form-row">
        <label>MySQL aadress
            <input name="localhost" type="text" class="input-field" id="localhost" tabindex="5" value="localhost" />
        </label>
        <div class="field-description">Andmebaasi aadress.</div>
    </div>
	</form>

  <span class="button form-button focused-button" id="install-btn">Valmis</span>
  <span class="button form-button" onclick="resetForm($('form[name=install]'));">T&#252;hjenda v&#228;ljad</span>
</div>
<div id="navigation-bar-container">
    <ul id="navigation-bar">
        <li id="logo">focus</li>
    </ul>
</div>
</body></html>